package com.study.leetcode;

/**编写一个函数来查找字符串数组中的最长公共前缀。
 如果不存在公共前缀，返回空字符串
 * @author Honglixi
 * @create 2021-03-21 8:50
 */
public class leetcode14 {
    public String longestCommonPrefix(String[] strs){
        if (strs.length == 0)
            return "";
        String ans = strs[0];//设最长公共前缀为第一个字符串
        for (int i =1;i < strs.length;i++){
            int j = 0;
            for (; j < ans.length() && j < strs[i].length(); j++) {
                if (ans.charAt(j) != strs[i].charAt(j))
                    break;
            }
            ans = ans.substring(0,j);
            if (ans.equals(""))
                return ans;
        }
        return ans;
    }

    public static void main(String[] args) {
        String[] arr;
        arr = new String[]{"flow","flower","flight","foeirjf"};
        leetcode14 test = new leetcode14();
        String longestCommonPrefix = test.longestCommonPrefix(arr);
        System.out.println(longestCommonPrefix);
    }
}
